//
//  LH_CLLocationManager.m
//  location
//
//  Created by 美食家 on 16/8/2.
//  Copyright © 2016年 不孤独的美食家. All rights reserved.
//

#import "LH_CLLocationManager.h"
#import <UIKit/UIKit.h>

@interface LH_CLLocationManager ()
{
    CLLocationCoordinate2D currentCoordinate;
    CLLocationManager *lh_manager;
    NSString          *cityName;
    NSString          *currentCity;
    NSString          *currentDetailAddress;
    NSString          *province;
    NSString          *detailAddress;
    NSString          *country;
    NSString          *postalCode;
    NSString          *thoroughfare;
    NSString          *errorCode;
}
@property (nonatomic, strong) LocationCorrrdinateBlock     locationBlock;
@property (nonatomic, strong) NSStringCityBlock            cityBlock;
@property (nonatomic, strong) NSStringDetailAddressBlock   addressBlock;
@property (nonatomic, strong) LocationErrorBlock           errorBlock;
@property (nonatomic, strong) NSStringThoroughfareBlock    thoroughfareBlock;
@property (nonatomic, strong) NSStringPostalCodeBlock      postalCodeBlock;
@property (nonatomic, strong) NSStringCountryBlock         countryBlock;
@property (nonatomic, strong) NSStringProvinceBlock        provincBlock;

@end

@implementation LH_CLLocationManager
+ (LH_CLLocationManager *)shareLocation{
    static dispatch_once_t token = 0;
    __strong static id _sharedLocation = nil;
    dispatch_once(&token, ^{
        _sharedLocation = [[self alloc] init];
    });
    return _sharedLocation;
}
- (void)lh_getCurrentLocationCoordinate:(LocationCorrrdinateBlock)locationtBlock
{
    self.locationBlock = [locationtBlock copy];
    [self startLocation];
}

- (void)lh_getCurrentLocationCoordinate:(LocationCorrrdinateBlock)locationtBlock withAddress:(NSStringDetailAddressBlock)addressBlock
{
    self.locationBlock = [locationtBlock copy];
    self.addressBlock = [addressBlock copy];
    [self startLocation];
}

- (void)lh_getCurrentDetailAddress:(NSStringDetailAddressBlock)addressBlock
{
    self.addressBlock = [addressBlock copy];
    [self startLocation];
}

- (void)lh_getCurrentProvince:(NSStringProvinceBlock)provinceBlock
{
    self.provincBlock = [provinceBlock  copy];
    [self startLocation];
}

- (void)lh_getCurrentCity:(NSStringCityBlock)cityBlock
{
    self.cityBlock = [cityBlock copy];
    [self startLocation];
}

-(void)lh_getCurrentThoroughfare:(NSStringThoroughfareBlock)thoroughfareBlock
{
    self.thoroughfareBlock=[thoroughfareBlock copy];
    [self startLocation];
}

-(void)lh_getCurrentCountry:(NSStringCountryBlock)countryBlock
{
    self.countryBlock=[countryBlock copy];
    [self startLocation];
}

-(void)lh_getCurrentPostalCode:(NSStringPostalCodeBlock)postalCodeBlock
{
    self.postalCodeBlock=[postalCodeBlock copy];
    [self startLocation];
}

-(void)lh_getLocationError:(LocationErrorBlock)errorBlock
{
    self.errorBlock=[errorBlock copy];
    [self startLocation];
}
#pragma mark - CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:[locations firstObject] completionHandler:^(NSArray *array, NSError *error){
        if (array.count > 0){
            CLPlacemark *placemark = [array objectAtIndex:0];
            /*
             @property (nonatomic, readonly, copy, nullable) NSString *name; // eg. Apple Inc.
             @property (nonatomic, readonly, copy, nullable) NSString *thoroughfare; // street name, eg. Infinite Loop
             @property (nonatomic, readonly, copy, nullable) NSString *subThoroughfare; // eg. 1
             @property (nonatomic, readonly, copy, nullable) NSString *locality; // city, eg. Cupertino
             @property (nonatomic, readonly, copy, nullable) NSString *subLocality; // neighborhood, common name, eg. Mission District
             @property (nonatomic, readonly, copy, nullable) NSString *administrativeArea; // state, eg. CA
             @property (nonatomic, readonly, copy, nullable) NSString *subAdministrativeArea; // county, eg. Santa Clara
             @property (nonatomic, readonly, copy, nullable) NSString *postalCode; // zip code, eg. 95014
             @property (nonatomic, readonly, copy, nullable) NSString *ISOcountryCode; // eg. US
             @property (nonatomic, readonly, copy, nullable) NSString *country; // eg. United States
             @property (nonatomic, readonly, copy, nullable) NSString *inlandWater; // eg. Lake Tahoe
             @property (nonatomic, readonly, copy, nullable) NSString *ocean; // eg. Pacific Ocean
             @property (nonatomic, readonly, copy, nullable) NSArray<NSString *> *areasOfInterest; // eg. Golden Gate Park
             */
            //            NSLog(@"--name--%@",placemark.name);
            //            NSLog(@"--thoroughfare--%@",placemark.thoroughfare);
            //            NSLog(@"--subLocality--%@",placemark.subLocality);
            //            NSLog(@"--locality--%@",placemark.locality);
            //            NSLog(@"--administrativeArea--%@",placemark.administrativeArea);
            //            NSLog(@"--subAdministrativeArea--%@",placemark.subAdministrativeArea);
            //            NSLog(@"--postalCode--%@",placemark.postalCode);
            //            NSLog(@"--ISOcountryCode--%@",placemark.ISOcountryCode);
            //            NSLog(@"--country--%@",placemark.country);
            //国家
            country=placemark.country;
            //省份
            province=placemark.administrativeArea;
            //城市
            cityName = [NSString stringWithFormat:@"%@",placemark.locality];
            //街道
            thoroughfare=placemark.thoroughfare;
            //经纬度
            currentCoordinate=CLLocationCoordinate2DMake(manager.location.coordinate.latitude, manager.location.coordinate.longitude);
            if (placemark.subThoroughfare) {
                detailAddress = [NSString stringWithFormat:@"%@%@%@%@%@%@",placemark.country,placemark.administrativeArea,placemark.locality,placemark.subLocality,placemark.thoroughfare,placemark.subThoroughfare];
            }else{
                detailAddress = [NSString stringWithFormat:@"%@%@%@%@%@",placemark.country,placemark.administrativeArea,placemark.locality,placemark.subLocality,placemark.thoroughfare];
            }
            if (placemark.postalCode) {
                postalCode=placemark.postalCode;
            }else{
                postalCode=@"没找到当前邮政编码";
            }
            errorCode=[NSString stringWithFormat:@"%@",error];
        }
        
        if (_locationBlock) {
            _locationBlock(currentCoordinate);
            _locationBlock = nil;
        }
        if (_cityBlock) {
            _cityBlock(cityName);
            _cityBlock = nil;
        }
        if (_addressBlock) {
            _addressBlock(detailAddress);
            _addressBlock = nil;
        }
        if (_provincBlock) {
            _provincBlock(province);
            _provincBlock=nil;
        }
        if (_thoroughfareBlock) {
            _thoroughfareBlock(thoroughfare);
            _thoroughfareBlock=nil;
        }
        if (_countryBlock) {
            _countryBlock(country);
            _countryBlock=nil;
        }
        if (_postalCodeBlock) {
            _postalCodeBlock(postalCode);
            _postalCodeBlock=nil;
        }
        if (_errorBlock) {
            _errorBlock(errorCode);
            _errorBlock=nil;
        }
    }];
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error
{
    [self stopLocation];
    
}
#pragma mark - 开始定位
-(void)startLocation
{
    if([CLLocationManager locationServicesEnabled] && [CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied)
    {
        lh_manager=[[CLLocationManager alloc]init];
        lh_manager.delegate=self;
        lh_manager.desiredAccuracy = kCLLocationAccuracyBest;
        [lh_manager requestAlwaysAuthorization];
        lh_manager.distanceFilter=100;
        [lh_manager startUpdatingLocation];
    }
    else
    {
        UIAlertController* alterVc=[UIAlertController alertControllerWithTitle:@"提示" message: @"需要开启定位服务,请到设置->隐私,打开定位服务"preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        }];
        [alterVc addAction:okAction];
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alterVc animated:YES completion:nil];
    }
}
#pragma mark - 停止定位
-(void)stopLocation
{
    lh_manager = nil;
}

@end
